package com.gopay.bis.pab.ebank.operation;


import java.security.KeyStore;

import com.gopay.bis.common.util.BankLogUtils;
import com.gopay.common.constants.proccode.ProcCodeConstants;
import com.gopay.common.domain.bank.BaseMessage;
import com.gopay.common.exception.GopayException;
import com.gopay.remote.bank.ICertHelper;
import com.sdb.payment.core.MerchantSignVerify;

/**
 * 平安B2B签名/验签类
 * 
 * @PabB2bCerthelper.java
 * @author lilili
 */
public class PabB2bCerthelper implements ICertHelper {
    // 配置文件名
    private String merchantName;


    /**
     * 签名
     * 
     * @param Object plainText
     * @return Object
     * @throws GopayException 
     */
	public String sign(BaseMessage bsaeMessage) throws GopayException {
    	try{
    		BankLogUtils.printB2BSignPlainLog(bsaeMessage);
    		String plainMessage = bsaeMessage.getPlainMessage();
            MerchantSignVerify mer = new MerchantSignVerify(merchantName);
            String signMessage = mer.merchantSignData_ABA(plainMessage);
            BankLogUtils.printB2BSignSignatureLog(bsaeMessage, signMessage);
            return signMessage;
    	}catch(Exception e){
    		BankLogUtils.printB2BSignExceptionLog(bsaeMessage, e);
			throw new GopayException(ProcCodeConstants.PROC_CODE_100E6028);
    	}
	}

    /**
     * 验签
     * 
     * @param Object plainText
     * @param Object signature
     * @return Object
     * @throws GopayException 
     */
	public Object verify(BaseMessage bsaeMessage) throws GopayException {
		try {
			String signMessage = bsaeMessage.getSignMessage();
			String plainMessage = bsaeMessage.getPlainMessage();
			/*
			 * MerchantSignVerify mer = new MerchantSignVerify(merchantName);
			 * boolean correct = mer.merchantVerifyPayGate_ABA(signMessage,
			 * plainMessage);
			 */

			VerifySignUtil verifySign = new VerifySignUtil();
			KeyStore keyStore = verifySign.KeyStoreUtil("/usr/local/ciecc/bankcerts/PAB/b2b/merchant_b2b.jks", "changeit");
			boolean correct = verifySign.verifyData(keyStore.getCertificate("sdb").getPublicKey(), signMessage, plainMessage, "MD5withRSA");
			BankLogUtils.printB2BVerifyPlainLog(bsaeMessage);
			BankLogUtils.printB2BVerifySignatureLog(bsaeMessage);
			BankLogUtils.printB2BVerifyResultLog(bsaeMessage, correct);
			return correct;
		}
		catch(Exception e){
			BankLogUtils.printB2BSignExceptionLog(bsaeMessage, e);
			throw new GopayException(ProcCodeConstants.PROC_CODE_100E6030);
    	}
	}


    public void setMerchantName(String merchantName) {
        this.merchantName = merchantName;
    }

}
